<template>
  <div class="message-statistics">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="statistics-cards">
      <el-col :span="6">
        <el-card shadow="hover" class="statistics-card">
          <template #header>
            <div class="card-header">
              <span>今日消息</span>
              <el-tag type="success">实时</el-tag>
            </div>
          </template>
          <div class="card-content">
            <div class="number">{{ todayStats.total }}</div>
            <div class="trend">
              <span>较昨日</span>
              <span :class="['trend-value', todayStats.trend >= 0 ? 'up' : 'down']">
                {{ Math.abs(todayStats.trend) }}%
                <el-icon>
                  <component :is="todayStats.trend >= 0 ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="statistics-card">
          <template #header>
            <div class="card-header">
              <span>未读消息</span>
              <el-tag type="warning">待处理</el-tag>
            </div>
          </template>
          <div class="card-content">
            <div class="number">{{ unreadStats.total }}</div>
            <div class="trend">
              <span>较昨日</span>
              <span :class="['trend-value', unreadStats.trend >= 0 ? 'up' : 'down']">
                {{ Math.abs(unreadStats.trend) }}%
                <el-icon>
                  <component :is="unreadStats.trend >= 0 ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="statistics-card">
          <template #header>
            <div class="card-header">
              <span>平均处理时长</span>
              <el-tag type="info">效率</el-tag>
            </div>
          </template>
          <div class="card-content">
            <div class="number">{{ efficiencyStats.avgTime }}</div>
            <div class="trend">
              <span>较上周</span>
              <span :class="['trend-value', efficiencyStats.trend >= 0 ? 'up' : 'down']">
                {{ Math.abs(efficiencyStats.trend) }}%
                <el-icon>
                  <component :is="efficiencyStats.trend >= 0 ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="statistics-card">
          <template #header>
            <div class="card-header">
              <span>消息阅读率</span>
              <el-tag type="primary">效果</el-tag>
            </div>
          </template>
          <div class="card-content">
            <div class="number">{{ readRateStats.rate }}%</div>
            <div class="trend">
              <span>较上周</span>
              <span :class="['trend-value', readRateStats.trend >= 0 ? 'up' : 'down']">
                {{ Math.abs(readRateStats.trend) }}%
                <el-icon>
                  <component :is="readRateStats.trend >= 0 ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="statistics-charts">
      <el-col :span="16">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>消息趋势</span>
              <div class="header-right">
                <el-radio-group v-model="trendTimeRange" size="small" @change="handleTrendTimeChange">
                  <el-radio-button label="week">近7天</el-radio-button>
                  <el-radio-button label="month">近30天</el-radio-button>
                  <el-radio-button label="year">近一年</el-radio-button>
                </el-radio-group>
              </div>
            </div>
          </template>
          <div class="chart-container" ref="trendChartRef"></div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>消息类型分布</span>
            </div>
          </template>
          <div class="chart-container" ref="typeChartRef"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="statistics-charts">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>处理效率分析</span>
              <div class="header-right">
                <el-select v-model="efficiencyTimeRange" size="small" @change="handleEfficiencyTimeChange">
                  <el-option label="今日" value="today" />
                  <el-option label="本周" value="week" />
                  <el-option label="本月" value="month" />
                </el-select>
              </div>
            </div>
          </template>
          <div class="chart-container" ref="efficiencyChartRef"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>渠道分布</span>
            </div>
          </template>
          <div class="chart-container" ref="channelChartRef"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 处理人统计 -->
    <el-card class="handler-statistics">
      <template #header>
        <div class="card-header">
          <span>处理人统计</span>
          <div class="header-right">
            <el-select v-model="handlerTimeRange" size="small" @change="handleHandlerTimeChange">
              <el-option label="今日" value="today" />
              <el-option label="本周" value="week" />
              <el-option label="本月" value="month" />
            </el-select>
          </div>
        </div>
      </template>
      <el-table
        :data="handlerStats"
        border
        style="width: 100%"
      >
        <el-table-column prop="handler" label="处理人" min-width="120" />
        <el-table-column prop="total" label="处理总数" width="120" />
        <el-table-column prop="completed" label="已完成" width="120" />
        <el-table-column prop="pending" label="待处理" width="120" />
        <el-table-column prop="avgTime" label="平均处理时长" width="150" />
        <el-table-column prop="efficiency" label="处理效率" width="120">
          <template #default="scope">
            <el-progress
              :percentage="scope.row.efficiency"
              :status="getEfficiencyStatus(scope.row.efficiency)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="satisfaction" label="满意度" width="120">
          <template #default="scope">
            <el-rate
              v-model="scope.row.satisfaction"
              disabled
              show-score
              text-color="#ff9900"
            />
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import {
  getMessageStatistics,
  getMessageTrend,
  getMessageTypeDistribution,
  getProcessEfficiency,
  getMessageChannelDistribution,
  getHandlerTodoStatistics
} from '@/api/message'

// 图表实例
let trendChart = null
let typeChart = null
let efficiencyChart = null
let channelChart = null

// 图表容器引用
const trendChartRef = ref(null)
const typeChartRef = ref(null)
const efficiencyChartRef = ref(null)
const channelChartRef = ref(null)

// 时间范围
const trendTimeRange = ref('week')
const efficiencyTimeRange = ref('week')
const handlerTimeRange = ref('week')

// 统计数据
const todayStats = ref({
  total: 0,
  trend: 0
})

const unreadStats = ref({
  total: 0,
  trend: 0
})

const efficiencyStats = ref({
  avgTime: '0分钟',
  trend: 0
})

const readRateStats = ref({
  rate: 0,
  trend: 0
})

const handlerStats = ref([])

// 初始化图表
const initCharts = () => {
  // 趋势图
  trendChart = echarts.init(trendChartRef.value)
  trendChart.setOption({
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['消息总数', '已读消息', '未读消息']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: []
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '消息总数',
        type: 'line',
        smooth: true,
        data: []
      },
      {
        name: '已读消息',
        type: 'line',
        smooth: true,
        data: []
      },
      {
        name: '未读消息',
        type: 'line',
        smooth: true,
        data: []
      }
    ]
  })

  // 类型分布图
  typeChart = echarts.init(typeChartRef.value)
  typeChart.setOption({
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        type: 'pie',
        radius: '50%',
        data: [],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  })

  // 效率分析图
  efficiencyChart = echarts.init(efficiencyChartRef.value)
  efficiencyChart.setOption({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['处理时长', '目标时长']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: {
      type: 'value',
      name: '分钟'
    },
    series: [
      {
        name: '处理时长',
        type: 'bar',
        data: []
      },
      {
        name: '目标时长',
        type: 'line',
        data: []
      }
    ]
  })

  // 渠道分布图
  channelChart = echarts.init(channelChartRef.value)
  channelChart.setOption({
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '20',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: []
      }
    ]
  })
}

// 获取统计数据
const fetchStatistics = async () => {
  try {
    const res = await getMessageStatistics()
    const { today, unread, efficiency, readRate } = res.data
    
    todayStats.value = today
    unreadStats.value = unread
    efficiencyStats.value = efficiency
    readRateStats.value = readRate
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 获取趋势数据
const fetchTrendData = async () => {
  try {
    const res = await getMessageTrend({ timeRange: trendTimeRange.value })
    const { dates, total, read, unread } = res.data
    
    trendChart.setOption({
      xAxis: {
        data: dates
      },
      series: [
        {
          data: total
        },
        {
          data: read
        },
        {
          data: unread
        }
      ]
    })
  } catch (error) {
    console.error('获取趋势数据失败:', error)
  }
}

// 获取类型分布数据
const fetchTypeDistribution = async () => {
  try {
    const res = await getMessageTypeDistribution()
    typeChart.setOption({
      series: [{
        data: res.data
      }]
    })
  } catch (error) {
    console.error('获取类型分布数据失败:', error)
  }
}

// 获取效率分析数据
const fetchEfficiencyData = async () => {
  try {
    const res = await getProcessEfficiency({ timeRange: efficiencyTimeRange.value })
    const { categories, actual, target } = res.data
    
    efficiencyChart.setOption({
      xAxis: {
        data: categories
      },
      series: [
        {
          data: actual
        },
        {
          data: target
        }
      ]
    })
  } catch (error) {
    console.error('获取效率分析数据失败:', error)
  }
}

// 获取渠道分布数据
const fetchChannelDistribution = async () => {
  try {
    const res = await getMessageChannelDistribution()
    channelChart.setOption({
      series: [{
        data: res.data
      }]
    })
  } catch (error) {
    console.error('获取渠道分布数据失败:', error)
  }
}

// 获取处理人统计数据
const fetchHandlerStats = async () => {
  try {
    const res = await getHandlerTodoStatistics({ timeRange: handlerTimeRange.value })
    handlerStats.value = res.data
  } catch (error) {
    console.error('获取处理人统计数据失败:', error)
  }
}

// 处理效率状态
const getEfficiencyStatus = (efficiency) => {
  if (efficiency >= 90) return 'success'
  if (efficiency >= 60) return 'warning'
  return 'exception'
}

// 时间范围变化处理
const handleTrendTimeChange = () => {
  fetchTrendData()
}

const handleEfficiencyTimeChange = () => {
  fetchEfficiencyData()
}

const handleHandlerTimeChange = () => {
  fetchHandlerStats()
}

// 窗口大小变化时重绘图表
const handleResize = () => {
  trendChart?.resize()
  typeChart?.resize()
  efficiencyChart?.resize()
  channelChart?.resize()
}

// 初始化
onMounted(() => {
  initCharts()
  fetchStatistics()
  fetchTrendData()
  fetchTypeDistribution()
  fetchEfficiencyData()
  fetchChannelDistribution()
  fetchHandlerStats()
  
  window.addEventListener('resize', handleResize)
})

// 清理
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  trendChart?.dispose()
  typeChart?.dispose()
  efficiencyChart?.dispose()
  channelChart?.dispose()
})
</script>

<style lang="scss" scoped>
.message-statistics {
  padding: 20px;

  .statistics-cards {
    margin-bottom: 20px;

    .statistics-card {
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }

      .card-content {
        text-align: center;

        .number {
          font-size: 24px;
          font-weight: bold;
          color: #303133;
          margin: 10px 0;
        }

        .trend {
          color: #909399;
          font-size: 14px;

          .trend-value {
            margin-left: 8px;
            font-weight: bold;

            &.up {
              color: #67c23a;
            }

            &.down {
              color: #f56c6c;
            }
          }
        }
      }
    }
  }

  .statistics-charts {
    margin-bottom: 20px;

    .chart-card {
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }

      .chart-container {
        height: 400px;
      }
    }
  }

  .handler-statistics {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
}
</style> 